package com.atguigu.service.sms.controller;

import com.atguigu.common_utils.utils.FormUtils;
import com.atguigu.common_utils.utils.RandomUtils;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.service.sms.consts.SmsConsts;
import com.atguigu.service.sms.phone.Phone;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@Api(tags = "短信接口")

@RestController
@RequestMapping("/api/send/sms")
public class SmsController {

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping
    public R sendSms(@RequestParam("mobile") String mobile){
        //校验手机格式是否正确
        boolean mobile1 = FormUtils.isMobile(mobile);
        if (!mobile1){
            throw new GuliException(ResultCodeEnum.LOGIN_PHONE_ERROR,
                    new RuntimeException(ResultCodeEnum.LOGIN_PHONE_ERROR.getMessage() ));
        }
        //判断验证码是否存在
        Boolean aBoolean = redisTemplate.hasKey(SmsConsts.MOBILE_COUNT_PERMIN_PREFIX + mobile);
        if (aBoolean){
            throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR_BUSINESS_LIMIT_CONTROL,
                    new RuntimeException("手机发送频繁"));
        }
        //是否超过当天发送最大次数
        Object o = redisTemplate.opsForValue().get(SmsConsts.MOBILE_COUNT_PERDAY_PREFIX + mobile);
        Integer count = 0;
        if (o!=null){
            count = (Integer) o;
            if (count>=3){
                throw new GuliException(ResultCodeEnum.SMS_SEND_ERROR_BUSINESS_MAX_CONTROL,
                        new RuntimeException(ResultCodeEnum.SMS_SEND_ERROR_BUSINESS_MAX_CONTROL.getMessage()));
            }
        }

        //1.生成验证码
        String code = RandomUtils.getFourBitRandom();
        //2.发送验证码
        Phone phone = new Phone();
        phone.sms(mobile,code,"60");
        //放入redis缓存中
        redisTemplate.opsForValue().set(SmsConsts.MOBILE_CODE_PREFIX+mobile,code,60, TimeUnit.MINUTES);
        //设置一分钟不能获取验证码
        redisTemplate.opsForValue().set(SmsConsts.MOBILE_COUNT_PERMIN_PREFIX+mobile,mobile,60,TimeUnit.SECONDS);
        //最大次数增加1 如果不存在 会从0开始加
        redisTemplate.opsForValue().increment(SmsConsts.MOBILE_COUNT_PERDAY_PREFIX+mobile);
        if (count==0){
            //设置24小时过期
            redisTemplate.expire(SmsConsts.MOBILE_COUNT_PERDAY_PREFIX+mobile,24,TimeUnit.HOURS);
        }
        return R.ok().data("data",code);
    }
}
